// ==UserScript==
// @name         JS刷视频
// @namespace    http://tampermonkey.net/
// @version      0.1.20220516
// @description  仅用于学习使用，网课自动挂机看视频，网课作业自动做题共享答案。网课在线辅助脚本❤网课辅助题库❤全自动化操作挂机【易全题库】
// @author       YanMing
// @match        *://www.baidu.com/*
// @match        *://*.uooconline.com/*
// @icon         
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // start
    start_console();
    start_uooc();
    // 输出
    function start_console() {
        const hello =
            "易全题库: \n" +
            "每一个星球都有一个驱动核心，每一种思想都有影响力的种子。\n"+
            " ......................阿弥陀佛......................\n" +
            "                       _oo0oo_                      \n" +
            "                      o8888888o                     \n" +
            '                      88" . "88                     \n' +
            "                      (| -_- |)                     \n" +
            "                      0\\  =  /0                     \n" +
            "                   ___/‘---’\\___                   \n" +
            "                  .' \\|       |/ '.                 \n" +
            "                 / \\\\|||  :  |||// \\                \n" +
            "                / _||||| -卍-|||||_ \\               \n" +
            "               |   | \\\\\\  -  /// |   |              \n" +
            "               | \\_|  ''\\---/''  |_/ |              \n" +
            "               \\  .-\\__  '-'  ___/-. /              \n" +
            "             ___'. .'  /--.--\\  '. .'___            \n" +
            '         ."" ‘<  ‘.___\\_<|>_/___.’>’ "".          \n' +
            "       | | :  ‘- \\‘.;‘\\ _ /’;.’/ - ’ : | |        \n" +
            "         \\  \\ ‘_.   \\_ __\\ /__ _/   .-’ /  /        \n" +
            "    =====‘-.____‘.___ \\_____/___.-’___.-’=====     \n" +
            "                       ‘=---=’                      \n" +
            "                                                    \n" +
            "...........佛祖保佑     永不挂科     考试必过..........";
        console.log( hello);
    };


    // 几倍播放进度(默认1倍,安全起见不超过2)
    let VIDEO_SPEED = 1;
    // 多久提交一次
    let VIDEO_TIMES = 10;
    // uooconline  start ...
    let UoocAutoLearn ={
        index:"",
        course_id: "",
        course_name: "",// 课程名称
        chapter_id: 0, // 当前章节
        section_id: "", // 内容部分
        resource_id: "", // 资源
        catalog_id: 0,
        task_id: 0,// 任务ID，考试ID
        video_pos:0,
        video_length:0,
        video_play_source: "",
        title: "",// 视频标题 XXX.mp4
        subsection_id: "",
        parent_name: "" // 课程信息
    }

    function start_uooc(){
        if (/^\/home/.test(location.pathname)) {
            if(/^#\/center\/course\/learn/.test(location.hash)){
                // 开课中
                change_uooc_course_learn_page();
            }else if(/^#\/center\/course\/finish/.test(location.hash)){
                // 已结束
            }else if(/^#\/center\/course\/nostart/.test(location.hash)){
                // 即将开始
            }else if(/^#\/center\/course\/follow/.test(location.hash)){
                // 关注的
            }
        } else if (/^\/home\/learn\/index/.test(location.pathname)) {

        } else if (/^\/exam\/paper/.test(location.pathname)) {

        }

    }

    function change_uooc_course (){
        UoocAutoLearn.index = "";
        UoocAutoLearn.course_id =  "";
        UoocAutoLearn.course_name =  "";// 课程名称
        UoocAutoLearn.chapter_id =  0; // 当前章节
        UoocAutoLearn.section_id =  ""; // 内容部分
        UoocAutoLearn.resource_id =  ""; // 资源
        UoocAutoLearn.catalog_id =  0;
        UoocAutoLearn.task_id =  0;// 任务ID，考试ID
        UoocAutoLearn.video_pos = 0;
        UoocAutoLearn.video_length = 0;
        UoocAutoLearn.video_play_source =  "";
        UoocAutoLearn.title =  "";// 视频标题 XXX.mp4
        UoocAutoLearn.subsection_id =  "";
        UoocAutoLearn.parent_name =  "" ;// 课程信息
    }

    /**
     * 添加'在线挂机'按钮
     */
    function change_uooc_course_learn_page(){
        console.log("尝试在开课中的课程，添加'在线挂机'按钮");
        // 延后执行(1s后添加按钮)
        setTimeout(() => {
            const courseArr = $('.course-item .course-right-bottom-btn').not('.uooc-auto-learn-btn');
            if(courseArr && courseArr.length>0){
                $('.course-item .course-right-bottom-btn').not('.uooc-auto-learn-btn').each(function (index, item) {
                    // 设置未修改过的
                    if (typeof item.dataset.btnAdd == "undefined") {
                        // http://cce.org.uooconline.com/home/course/课程ID号
                        var courseId = item.href.substr(item.href.lastIndexOf("/")+1);
                        if(!courseId){
                            courseId = item.pathname.split('/').pop();
                        }

                        var courseName = $('.course-name')[index].innerText;
                        var courseTeacher = $('.course-teacher')[0].innerText;
                        console.log("添加“在线挂机”按钮 --> "+courseName+"["+courseId+"] "+courseTeacher);
                        if (courseId) {
                            // 按钮
                            var btnHtml = '<a class="course-right-bottom-btn uooc-auto-learn-btn" style="font-size: 12px; width: 58px; margin-left: 4px;" data-index="' + index + '" data-cid="' + courseId + '" data-cname="' + courseName + '">在线挂机</a>';
                            // 设置为已修改
                            item.dataset.btnAdd = 'isAdd';
                            // 修改样式
                            item.style.fontSize = '12px';
                            item.style.width = '58px';
                            // 追加元素
                            $(item).before(btnHtml);
                        }
                    }
                });
                // 绑定按钮事件
                $(document).on('click', '.uooc-auto-learn-btn', function () {
                    var courseId = this.dataset.cid;
                    var courseName = this.dataset.cname;
                    var index = this.dataset.index;
                    if(courseId){
                        if(UoocAutoLearn.course_id){
                            console.log('当前已有挂机任务正在执行，'+UoocAutoLearn.course_name+"["+UoocAutoLearn.course_id+"]");
                            console.log('=====>更换在线挂机任务，'+courseName+"["+courseId+"]");
                        }else{
                            console.log('=====>开始在线挂机任务，'+courseName+"["+courseId+"]");
                        }
                        change_uooc_course();
                        UoocAutoLearn.index = index;
                        UoocAutoLearn.course_id = courseId;
                        UoocAutoLearn.course_name = courseName;
                        select_uooc_course_learn_progress()
                    }
                });
            }
        }, 1000);
    }

    /**
     * 查询当前课程学习进度
     */
    function select_uooc_course_learn_progress(){
        $.ajax({
            type: "GET",
            url: '/home/learn/getCourseLearn',
            data: {
                cid: UoocAutoLearn.course_id
            },
            success: function (response) {
                if (response.code == 1) {
                    UoocAutoLearn.chapter_id = response.data.chapter_id;
                    UoocAutoLearn.section_id = response.data.section_id;
                    UoocAutoLearn.resource_id = response.data.resource_id;
                    UoocAutoLearn.catalog_id = response.data.catalog_id;
                    UoocAutoLearn.subsection_id = response.data.subsection_id;
                    UoocAutoLearn.parent_name = response.data.parent_name;

                    // 如果没有看过
                    if (UoocAutoLearn.chapter_id <= 0) {
                        // 获取章节信息
                        select_uooc_course_catalog_list()
                    } else {
                        // 看过章节，获取课程观看时间（进度）
                        select_uooc_course_catalog_unit_learn()
                    }
                }
            }
        });
    }

    /**
     * 获取章节信息
     */
    function select_uooc_course_catalog_list(){
        $.ajax({
            type: "GET",
            url: '/home/learn/getCatalogList',
            data: {
                cid: UoocAutoLearn.course_id
            },
            success: function (response) {
                  if (response.code == 1) {
                    start_uooc_course_catalog_loop(response.data);
                }

            }
        });
    }

    /**
     * 遍历课程章节，查看每个章节是否完成
     * @param data
     */
    function start_uooc_course_catalog_loop(data){
        var isFinished = true;
        for (let index = 0; index < data.length; index++) {
            const item = data[index];
            if (item.finished == 0) {
                isFinished = false;
                if (typeof item.children != 'undefined') {
                    // 看当前目录是否有视频？？？？？
                    // 有二级目录，进行遍历，根目录有需要学习的,播放这个课程
                    start_uooc_course_catalog_loop(item.children);
                    break;
                } else {
                    // 播放这个课程
                    console.log('新的章节',item.name, item.id, item.pid );
                    UoocAutoLearn.catalog_id = item.id;
                    UoocAutoLearn.chapter_id = item.pid;
                    UoocAutoLearn.video_pos = 0;
                    // 开始下一课程
                    select_uooc_course_catalog_unit_learn();
                    break;
                }
            }
        }
        if (isFinished) {
            console.log("======>恭喜，"+UoocAutoLearn.course_name+"["+UoocAutoLearn.course_id+"] 课程已全看完。");
        }
    };

    /**
     * 获看过章节，获取课程观看时间（进度）
     */
    function select_uooc_course_catalog_unit_learn(){
        $.ajax({
            type: "GET",
            url: '/home/learn/getUnitLearn',
            data: {
                cid: UoocAutoLearn.course_id,
                chapter_id: UoocAutoLearn.chapter_id,
                section_id: UoocAutoLearn.section_id,
                subsection_id: UoocAutoLearn.subsection_id,// 有无改参数不影响，catalog_id一定要对
                catalog_id: UoocAutoLearn.catalog_id,
            },
            success: function (response) {
                if(response.code == 1 && response.data && response.data.length>0){
                    // 遍历每一个视频
                    let isFinished = true;
                    for (let index = 0; index < response.data.length; index++) {
                        const item = response.data[index];
                        UoocAutoLearn.resource_id = '';
                        if (item.finished == 0) {
                            if(item.type == 10 && item.video_play_list && item.video_play_list.length>0){
                                // 是视频，继续播放，还未看完
                                UoocAutoLearn.video_pos = parseFloat(item.video_pos);
                                UoocAutoLearn.video_play_source = item.video_play_list[0].source;
                                UoocAutoLearn.title = item.title;
                                UoocAutoLearn.resource_id = item.id;
                                isFinished = false;
                                // 获取视频时长
                                select_uooc_course_catalog_video_length()
                                break;
                            }else if( item.type == 60 && item.content && item.h5_url){
                                // 文本任务跳过，不处理
                                continue;
                            }else if(item.type == 80 && item.task_id){
                                // 考试
                                isFinished = false;
                                console.warn("需要进行章节测验,请在弹出的窗体中完成测验！")
                                UoocAutoLearn.task_id = item.task_id;
                                UoocAutoLearn.resource_id = item.id;
                                chanage_uooc_course_test_page()
                                break;
                            }else{
                                // 其他非视频，新页面显示
                                console.warn("暂不支持！type="+item.type)
                                continue;
                            }

                        }
                    }


                    // 如果都看完了
                    if (isFinished) {
                        // 获取下一节课
                        select_uooc_course_catalog_list();
                    }
                }

            }
        });
    }

    /**
     * 获取视频长度
     */
    function select_uooc_course_catalog_video_length(){
        const obj = $('.course-cover')[UoocAutoLearn.index];
        let video = document.createElement("video");
        //video.setAttribute("width", "320");
        //video.setAttribute("height", "240");
        video.setAttribute("controls", "controls");
        video.setAttribute("src", UoocAutoLearn.video_play_source);
        obj.appendChild(video);
        // 加载完成后调用
        //video.onloadedmetadata = function() {
        video.onloadeddata = function () {
            //console.log(video.duration); //打印时长
            UoocAutoLearn.video_length = video.duration;
        }
        //console.log(UoocAutoLearn.course_name+"["+UoocAutoLearn.course_id+"], "+ UoocAutoLearn.title+' ===> 总时长'+UoocAutoLearn.video_length+'秒, 已看至'+ UoocAutoLearn.video_pos+'秒');
        // 开始刷新时间,每X秒提交一次
        start_uooc_course_auto_learn_video();
        return;
    }
    /**
     * 开始自动挂机学习,提交课程观看进度，刷新时间
     * 开始刷新时间,每X秒提交一次
     */
    function start_uooc_course_auto_learn_video(){
        // 几倍播放进度(默认1倍) VIDEO_SPEED,多久提交一次VIDEO_TIMES
        if(VIDEO_SPEED<=1){
            VIDEO_SPEED = 1;
        }else if(VIDEO_SPEED>2){
            VIDEO_SPEED = 2;
        }
        UoocAutoLearn.video_pos = UoocAutoLearn.video_pos + (VIDEO_SPEED * VIDEO_TIMES);
        if (UoocAutoLearn.video_pos >= UoocAutoLearn.video_length && UoocAutoLearn.video_length > 0) {
            UoocAutoLearn.video_pos = UoocAutoLearn.video_length;
        }
        $.ajax({
            type: "POST",
            url: '/home/learn/markVideoLearn',
            data: {
                chapter_id: UoocAutoLearn.chapter_id,
                cid: UoocAutoLearn.course_id,
                // hidemsg_: true,
                network: 3,
                resource_id: UoocAutoLearn.resource_id,
                section_id: UoocAutoLearn.section_id,
                source: 1,
                subsection_id: UoocAutoLearn.subsection_id,
                video_length: UoocAutoLearn.video_length,
                video_pos: UoocAutoLearn.video_pos
            },
            success: function (response) {
                if (response.code !== 1) {
                    console.log('Error', response);
                    console.warn("出现异常，暂停任务。",response.msg,UoocAutoLearn.course_name+"["+UoocAutoLearn.course_id+"], "+ UoocAutoLearn.title+"["+UoocAutoLearn.chapter_id+"]");
                    return;
                }
                console.log(
                    ' 当前课程 ', UoocAutoLearn.parent_name,
                    ' 观看内容 ', UoocAutoLearn.title,"["+UoocAutoLearn.chapter_id+","+UoocAutoLearn.section_id+","+UoocAutoLearn.resource_id+"]",
                    ' 已看至 ', UoocAutoLearn.video_pos, '秒',
                    ' 总时长 ',   UoocAutoLearn.video_length == 0 ? '未知' : UoocAutoLearn.video_length, '秒'
                );
                if (response.data.finished == 1 || (UoocAutoLearn.video_length > 0 && UoocAutoLearn.video_pos >= UoocAutoLearn.video_length)) {
                    console.log("======> 恭喜 "+UoocAutoLearn.course_name+"["+UoocAutoLearn.course_id+"] 本课已经结束");
                    // 获取下一节课
                    select_uooc_course_catalog_list();
                    return;
                }
                // 开始刷新时间,X秒后再提交一次
                setTimeout(() => {
                    start_uooc_course_auto_learn_video();
                }, VIDEO_TIMES * 1000);

            }
        });
    }

    /**
     * 章节测验
     */
    function chanage_uooc_course_test_page(){
        let contentURl = '';
        if(UoocAutoLearn.subsection_id && UoocAutoLearn.resource_id){
            contentURl='/home/learn/index#/'+UoocAutoLearn.course_id+'/'+UoocAutoLearn.chapter_id+'/'+UoocAutoLearn.section_id+'/'+UoocAutoLearn.subsection_id+'/'+UoocAutoLearn.resource_id+'/subsection';
        }else if(UoocAutoLearn.section_id && UoocAutoLearn.resource_id){
            contentURl='/home/learn/index#/'+UoocAutoLearn.course_id+'/'+UoocAutoLearn.chapter_id+'/'+UoocAutoLearn.section_id+'/'+UoocAutoLearn.resource_id+'/section';
        }else{
            contentURl = '/home/learn/index#/'+UoocAutoLearn.course_id+'/'+UoocAutoLearn.chapter_id+'/'+UoocAutoLearn.section_id;
        }
        const layerIndex = layer.open({
            type: 2,
            title: false,
            shadeClose: true, // 遮罩关闭
            shade: 0.5, // 遮罩透明度
            closeBtn: 0, //不显示关闭按钮
            offset: 'r', // 弹出层位置
            area: ['90%', '100%'], // 大小
            anim: 3, // 动画 向左滑动
            content: contentURl
        });

        // 模拟关闭(查詢答案)
        setTimeout(() => {
            layer.close(layerIndex);
        }, 3000);
    }


})();

